﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    ItemBaseEditor(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Dialog);

    table = TD_ITEM;
    openViewFlag=true;
    hostName=QSysInfo::machineHostName();
    itemModel=new QStandardItemModel(this);
    view=new ItemView(this);
    ui->treeView->setModel(itemModel);
    ui->treeView->setEditTriggers(QTreeView::NoEditTriggers);

    createTray();
    updateView();
    createMenu();
    flushTimer=startTimer(FLUSH_TIME * 1000);

    loadLocation();
}

Dialog::~Dialog()
{
    flushSpoor();
    saveLocation();
    delete ui;
}

void Dialog::createTray()
{
    tray_Menu=new QMenu(this);
    tray_Menu->addAction(QStringLiteral("退出"),QApplication::quit);
    tray=new QSystemTrayIcon(QIcon(":/quick.ico"),this);
    tray->setContextMenu(tray_Menu);
    tray->setToolTip(QString::number(SP_VER) + QStringLiteral(" - 快捷回复运行中"));

    connect(tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this,SLOT(trayActivated(QSystemTrayIcon::ActivationReason))
            );
    tray->show();
}

void Dialog::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
    if(reason == QSystemTrayIcon::DoubleClick)
    {
        if(this->isVisible())
            this->hide();
        else
            this->show();
    }
}

void Dialog::timerEvent(QTimerEvent *event)
{
    int id=event->timerId();
    if(id == flushTimer)
        flushSpoor();
    else if(id == cleanTimer)
    {
        ui->status->clear();
        //      itemView->hide();
        killTimer(cleanTimer);
    }
}

void Dialog::flushSpoor()
{
    if(spoor.isEmpty())
        return;

    QMap<QString,int>::ConstIterator itor;
    for(itor = spoor.cbegin();itor !=spoor.cend();itor++ )
    {
        QSqlQuery query;
        query.prepare(QString("insert into %1 (time,host,label,tick) values (?,?,?,?)").arg(TD_TRACE));
        query.addBindValue(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
        query.addBindValue(hostName);
        query.addBindValue(itor.key());
        query.addBindValue(itor.value());
        if(!query.exec())
            qDebug()<<query.lastError().text();
    }
    spoor.clear();
}

void Dialog::updateView()
{
    updateView_One();
    ui->treeView->resizeColumnToContents(0);
}

void Dialog::generateMenu()
{
    if(!menu->isEmpty())
    {
        menu->clear();
        menu->disconnect();
    }

    menu->addAction(QStringLiteral("添加..."),this,&Dialog::newItem);
    menu->addAction(QStringLiteral("编辑..."),this,&Dialog::editItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("【删除】"),this,&Dialog::removeItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新"),this,&Dialog::updateView);
    if(openViewFlag)
        menu->addAction(QStringLiteral("禁用查看器"),this,&Dialog::detectOpenView);
    else
        menu->addAction(QStringLiteral("启用查看器"),this,&Dialog::detectOpenView);
    menu->addAction(QStringLiteral("全部折叠"),this,&Dialog::collapseAll);
}

void Dialog::detectOpenView()
{
    if(openViewFlag)
        openViewFlag=false;
    else
        openViewFlag=true;

    generateMenu();
}

void Dialog::collapseAll()
{
    ui->treeView->collapseAll();
}

void Dialog::newItem()
{
    if(view != nullptr && view->isVisible())
        view->hide();

    ItemAdd itemAdd(this,table);
    itemAdd.move(this->x() + this->width() + 20,this->y());

    QModelIndex index=ui->treeView->currentIndex();
    if(getCategoryByIndex(index))
        itemAdd.setCategory(category);

    if(itemAdd.exec() == QDialog::Accepted)
        updateView();
}

void Dialog::removeItem()
{
    QModelIndex index=ui->treeView->currentIndex();
    if(!index.isValid())
        return;

    if(!getItemByIndex(index))
        return;

    QMessageBox::StandardButton btn=QMessageBox::warning(this,QStringLiteral("操作确认"),QStringLiteral("确定删除？无法撤销！"),
                                                         QMessageBox::Cancel | QMessageBox::Ok,
                                                         QMessageBox::Cancel );
    if(btn == QMessageBox::Ok)
    {
        QSqlQuery query;
        QString sql=QString("delete from %1 where category='%2' and label='%3'")
                .arg(table)
                .arg(category)
                .arg(label);
        if(query.exec(sql))
            updateView();
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("异常情况，删除失败！"));
    }
}

void Dialog::editItem()
{
    if(view != nullptr && view->isVisible())
        view->hide();

    QModelIndex index=ui->treeView->currentIndex();
    if(!getItemByIndex(index))
        return;

    QSqlQuery query;
    QString sql=QString("select id from %1 where category='%2' and label='%3'")
            .arg(table)
            .arg(category)
            .arg(label);

    query.exec(sql);
    if(query.next())
    {
        int id=query.value("id").toInt();
        ItemEdit itemEdit(id,this,table);
        itemEdit.move(this->x() + this->width() + 20,this->y());
        if(itemEdit.exec() == QDialog::Accepted)
            updateView();
    }
}

void Dialog::showItemView(const QString &label,const QString &detail)
{
    view->move(this->x() + this->width() + 20,this->y());
    view->setWindowTitle(label);
    view->display(detail);

    if(!view->isVisible())
        view->show();
}

void Dialog::on_treeView_clicked(const QModelIndex &index)
{
    if(!openViewFlag)
    {
        if(view->isVisible())
            view->hide();
        return;
    }

    if(!getItemByIndex(index))
        return;

    if(!getDetail())
        return;

    if(detail.isEmpty())
        return;

    showItemView(label,detail);
}

void Dialog::on_treeView_doubleClicked(const QModelIndex &index)
{
    if(!index.isValid())
        return;

    if(!openViewFlag)
    {
        if(!getItemByIndex(index))
            return;

        if(!getDetail())
            return;

        if(detail.isEmpty())
            return;

        if(detail.startsWith(PRE_CDN))
        {
            QString fileName=detail;
            fileName=fileName.remove(PRE_CDN);
            QString filePath=P_FHS_CACHE + fileName;
            if(QFile::exists(filePath))
            {
                QImage img(filePath);
                if(img.isNull())
                    return;
                qApp->clipboard()->setImage(img);
            }
        }
        else
            qApp->clipboard()->setText(detail);
    }
    else
    {
        //双击会先执行单击
        switch (view->getViewType()) {
        case VT_NULL:
            return;
        case VT_TEXT:
            qApp->clipboard()->setText(detail);
            break;
        case VT_IMG:
            QImage img=view->getImage();
            if(img.isNull())
                return;
            qApp->clipboard()->setImage(img);
            break;
        }
    }
    ui->status->setText(QStringLiteral("已复制到剪贴板"));
    cleanTimer=startTimer(4000);

    if(spoor.contains(label))
    {
        int tick=spoor.value(label);
        spoor.insert(label,++tick);
    }
    else
        spoor.insert(label,1);
}

void Dialog::on_input_returnPressed()
{
    QString input=ui->input->text().trimmed();
    if(input.isEmpty())
        return;

    form=WF_SEARCH;
    showSearchView(input);
    ui->input->clear();
}
